// server/ctrls/reviews.js
const db = require('../common/db');
const sql = require('../common/sql');

module.exports = {
    reviewsBygid: (req, res) => {
        let gid = req.body.gid;
        db.query(sql.reviews.reviewsBygid, [gid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, reviews: results });
            }
        });
    },
    addReview: (req, res) => {
        let { gid, userid, contents, package, speed, service, product } = req.body;
        let rvtime = new Date().toLocaleString();
       

        const imgs = req.files ? req.files.map(file => file.filename) : [];
       const imgStr = imgs.join(',');  // 将多个文件名用逗号拼接存储

        

        db.query(sql.reviews.addReview, [gid, userid, contents, rvtime, imgStr, package, speed, service, product], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: '查询数据库错误！', err: err });
            } else {
                res.send({ code: 200, msg: '评价成功', data: { reviewId: results.insertId } });
            }
        });
    },
     userReviews: (req, res) => {
        let userid = req.body.userid;
        db.query(sql.reviews.userReviews, [userid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, reviews: results });
            }
        })
    },
    updatereviews: (req, res) => {
        let { gid, userid, contents, rvid } = req.body;
        db.query(sql.reviews.updatereviews, [gid, userid, contents, rvid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, reviews: results });
            }
        })
    },
    addreviews: (req, res) => {
        let { gid, userid, contents, rvtime, rvid } = req.body;
        db.query(sql.reviews.addreviews, [gid, userid, contents, rvtime, rvid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, reviews: results });
            }
        })
    },
    delreviews: (req, res) => {
        let { rvid } = req.body;
        db.query(sql.reviews.delreviews, [rvid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, reviews: results });
            }
        })
    }
};
